package com.github.phoenics.teacher.itheima.netty.protobuf;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 服务器端代码
 *
 * @author Phoenics Chow
 * on 2020年02月17日
 */
public class SubReqServer {
    public void bind(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // protobufDecoder仅仅负责反序列化，并不支持读半包，所以在之前，一定要有读半包的处理器。
                            // 有三种方式可以选择：
                            // 使用netty提供ProtobufVarint32FrameDecoder
                            // 继承netty提供的通用半包处理器 LengthFieldBasedFrameDecoder
                            // 继承ByteToMessageDecoder类，自己处理半包
                            // 半包的处理
                            socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder()) //解码器
                                    // 需要处理的目标类
                                    .addLast(new ProtobufDecoder(SubscribeReqProto.SubscribeReq.getDefaultInstance()))
                                    //这里需要加入处理半包处理的规则
                                    .addLast(new ProtobufVarint32LengthFieldPrepender())
                                    //protobuf格式的序列化编码
                                    .addLast(new ProtobufEncoder())
                                    //业务逻辑
                                    .addLast(new SubReqServerHandler());
                        }
                    });
            //绑定端口,同步等待成功
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int port =8080;
        if (args!=null&&args.length>0){
            try{
                port = Integer.valueOf(args[0]);
            }catch (NumberFormatException e){

            }
        }
        new SubReqServer().bind(port);
    }
}